<template>
    <div>
        <h2>文章编辑</h2>
        {{ id }}
        <div style="border: 1px solid #ccc">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                mode="default" />
            <Editor style="height: 300px; overflow-y: hidden;" v-model="content" :defaultConfig="editorConfig"
                mode="default" @onCreated="handleCreated" />
        </div>
        <div style="margin-top: 20px;">
            <el-button type="primary" @click="changeSubmit">确定修改</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import { _artiCleDetail, _artiCleEdit } from "@/api/article";
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'



let $route = useRoute()

// 获取上个页面传过来的id
let id = $route.query.id as unknown as string
let content = ref("")

// 拿到文章id之后获取文章详情-渲染
getData()

async function getData() {
    let res = await _artiCleDetail({
        id
    })
    console.log(25, res);
    content.value = res.data.content
}


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 菜单栏的信息
const toolbarConfig = {
    // insertKeys: {
    //     index: 5, // 插入的位置，基于当前的 toolbarKeys
    //     keys: ['menu-key1', 'menu-key2']
    // }
}

const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

let $router = useRouter()
let changeSubmit = async () => {
    console.log(content);
    let res = await _artiCleEdit({
        id,
        content: content.value
    })
    if (res.data.code == 0) {
        ElMessage({
            message: res.data.msg,
            type: 'success',
        })
        $router.back()
    }
}
</script>

<style scoped></style>